package com.waitingsnow.core.util.core
{
import com.waitingsnow.core.debug.Logger;

import flash.external.ExternalInterface;
import flash.net.URLVariables;

/**
 * as与js相互调用
 * @author waitingsnow
 * $Id: ExternalUtil.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class ExternalUtil
{
	/**
	 * 调用js函数
	 * @param methodName
	 * @param args
	 * @return 
	 * 
	 */	
	static public function call(methodName:String, ...args):*
	{
		var result:*;
		if (ExternalInterface.available)
		{
			Logger.info("call js: " + methodName + "(" + args.toString() + ")");
			args.unshift(methodName);
			result = ExternalInterface.call.apply(null, args);
		}
		return result;
	}
	
	/**
	 * 回调js函数
	 * @param methodName
	 * @param method
	 * 
	 */	
	static public function callback(methodName:String, method:Function):void
	{
		if (ExternalInterface.available)
		{
			try
			{
				ExternalInterface.addCallback(methodName, method);
			}
			catch (e:Error)
			{
				Logger.log(methodName + " callback failer!" + e.toString());
			}
		}
	}
	
	/**
	 * 获取url地址中的变量
	 * @param url
	 * @return 
	 * 
	 */	
	public static function getURLVariables(url:String):URLVariables
	{
		var params:String;
		if (url.indexOf('#') != -1)
		{
			params = url.slice(url.indexOf('#') + 1);
		}
		else if (url.indexOf('?') != -1)
		{
			params = url.slice(url.indexOf('?') + 1);
		}
		var vars:URLVariables = new URLVariables();
		params && vars.decode(params);
		return vars;
	}
}
}